'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
 
exports.main = async (event, context) => {
	let rechargeDatas = await db.collection('wmz-entitlement-recharge').where({
		recharge_status_text: "充值中"
	}).limit(100).orderBy('create_time', 'desc').get()
	rechargeDatas = rechargeDatas.data
	console.log(rechargeDatas.length)
	let res
	for (var i in rechargeDatas) {
		let rechargeSdk = uniCloud.importObject('wmz-recharge-sdk')
		let appId = ""
		let apiKey = ""
		if (rechargeDatas[i].app_id === "0375964d64e56d470223e6a059620ffe") {
			const mycloud = uniCloud.init({
				provider: 'tencent',
				spaceId: 'tcb-m6g9aep66mev6ffd19470-4faedb'
			})
			rechargeSdk = mycloud.importObject('wmz-recharge-sdk')
		} else {
			let appletInfo = await db.collection('wmz-applet-info').doc(rechargeDatas[i].app_id).get()
			appletInfo = appletInfo.data[0]
			if (appletInfo) {
				appId = appletInfo.recharge_app_id
				apiKey = appletInfo.api_key
			}
		}
		let ordersn = rechargeDatas[i].ordersn
		res = await rechargeSdk.order({
			tradenos: rechargeDatas[i]._id,
			page: 1,
			psize: 100
		},appId,apiKey)
		console.log(res)
		if (res.status === 200) {
			if (res.data.code === 1) {
				let data = res.data.list[0]
				if (data) {
					let status = data.status
					if (status != 1) {
						if (status === 2) {
							status = "充值成功"
						} else if (status === 3) {
							status = "充值失败"
						}
						await db.collection('wmz-entitlement-recharge').doc(rechargeDatas[i]._id).update({
							recharge_status_text: status
						})
					}else{
						let aremark=data.aremark
						if(aremark){
							await db.collection('wmz-entitlement-recharge').doc(rechargeDatas[i]._id).update({
								recharge_status_text: "充值中-"+aremark
							})
						}
					}
				}
			}
		}
	}
	return event
};